//
//  AppDelegate.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/6/29.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginVC.h"
#import "MyShipmentDetailVC.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    if ([User isLogin]) {
        MainTabBarController *mainVC = [[MainTabBarController alloc] init];
        self.window.rootViewController = mainVC;
    }else {
        LoginVC *loginVC = [[LoginVC alloc] init];
    MainNavigationController *nav = [[MainNavigationController alloc] initWithRootViewController:loginVC];
        self.window.rootViewController = nav;
    }
    [self setUpKeyboard];
    [self.window makeKeyAndVisible];
    [self setJPush:launchOptions];
    return YES;
}

- (void)setUpKeyboard {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //默认为YES，关闭为NO
    manager.enable = YES;
    //键盘弹出时，点击背景，键盘收回
    manager.shouldResignOnTouchOutside = YES;
    //如果YES，那么使用textField的tintColor属性为IQToolbar，否则颜色为黑色。默认是否定的。
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    //如果YES，则在IQToolbar上添加textField的占位符文本。默认是肯定的。
    manager.shouldShowToolbarPlaceholder = YES;
    //设置IQToolbar按钮的文字
    manager.toolbarDoneBarButtonItemText = @"完成";
    //隐藏键盘上面的toolBar,默认是开启的
    manager.enableAutoToolbar = NO;
}

- (void)setJPush:(NSDictionary *)launchOptions {
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        if (@available(iOS 10.0, *)) {
            [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionAlert|
                                                              UNAuthorizationOptionBadge|
                                                              UNAuthorizationOptionSound)
                                                  categories:nil];
        }
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    [JPUSHService setupWithOption:launchOptions appKey:@"07472fa126a5f1c6ff221433"
                          channel:@"Publish channel"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    [self apService];
}

//注册 APNs 成功并上报 DeviceToken
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

//实现注册 APNs 失败接口（可选）
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification API_AVAILABLE(ios(10.0)){
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
    }else{
        //从通知设置界面进入应用
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}

// iOS 10 Support 收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"收到的通知++%@",userInfo);
//    NSString *type = [userInfo objectForKey:@"type"];
//    if ([type isEqualToString:@"message"]) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:DiningCarNewMessageRefresh object:nil];
//    }else if ([type isEqualToString:@"order"]) {
//        NSLog(@"收到通知刷新--%@",userInfo);
//        [[NSNotificationCenter defaultCenter] postNotificationName:DiningCarNewOrderRefresh object:nil];
//    }
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support 点击通知进入app
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler  API_AVAILABLE(ios(10.0)){
    // Required
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    int msgcode = [[userInfo objectForKey:@"msgcode"] intValue];
    if (msgcode == 3 || msgcode == 4) {
        NSString *wa_id = [userInfo objectForKey:@"wa_id"];
        MyShipmentDetailVC *vc = [MyShipmentDetailVC new];
        vc.wa_id = wa_id;
        vc.hidesBottomBarWhenPushed = YES;
        [[FactoryMethod getCurrentVC].rt_navigationController pushViewController:vc animated:YES];
    }
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService resetBadge];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)apService {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
}

- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = notification.userInfo;
    NSLog(@"接收到自定义消息:%@",userInfo);
    NSString *type = [[userInfo objectForKey:@"extras"] objectForKey:@"type"];
//    if ([type isEqualToString:@"message"]) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:DiningCarNewMessageRefresh object:nil];
//    }else if ([type isEqualToString:@"order"]) {
//        NSLog(@"收到自定义消息刷新--%@",userInfo);
//        [[NSNotificationCenter defaultCenter] postNotificationName:DiningCarNewOrderRefresh object:nil];
//    }
}

//  收到推送后
- (void)didGetNotificationToChangedNewsVCReloadData:(NSDictionary *)userInfo{

}

- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"极光注册失败%@", error);
}

//app进入前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [JPUSHService resetBadge];
}

@end
